import time
from django.db import models
from django.core.validators import MinValueValidator
from Dify.models.other import *

# 销售订单
class FaKuyouGoodsSalesOrder(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '销货'),
        ('2', '退货'),
    ]

    STATUS_CHOICES = [
        ('0', '未出库'),
        ('1', '全部出库'),
        ('2', '部分出库'),
        ('3', '已取消'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', null=True, blank=True,
                                     verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    receiving_address = models.CharField(max_length=255, null=True, blank=True, verbose_name='收货地址')
    sale_user = models.IntegerField(null=True, blank=True, verbose_name='销售员ID')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    discount = models.FloatField(default=10.00, validators=[MinValueValidator(0)], verbose_name='折扣率(%)')
    preferential_rate = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='优惠率(%)')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠金额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                    validators=[MinValueValidator(0)], verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='0', null=True, blank=True,
                              verbose_name='状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', null=True, blank=True,
                                    verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0', null=True, blank=True,
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    store_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                       validators=[MinValueValidator(0)], verbose_name='出库数量')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    note = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                  verbose_name='本次欠款')
    all_arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='总欠款')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())

    class Meta:
        db_table = 'fa_kuyou_goods_sales_order'
        verbose_name = '销货订单'
        verbose_name_plural = '销货订单'

    def __str__(self):
        return f"{self.purchase_code or '无编号'}-{self.get_purchase_type_display()}"


# 销售订单详情单
class FaKuyouGoodsSalesOrderInfo(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '销货'),
        ('2', '退货'),
    ]

    STATUS_CHOICES = [
        ('0', '未出库'),
        ('1', '全部出库'),
        ('2', '部分出库'),
        ('3', '已取消'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', null=True,
                                     blank=True, verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    receiving_address = models.CharField(max_length=255, null=True, blank=True, verbose_name='收货地址')
    sale_user = models.IntegerField(null=True, blank=True, verbose_name='销售员ID')
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品备注')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性ID')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位ID')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库ID')
    allow_stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='可用库存')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    purchase_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='可生成购货单数量')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='基本单位ID')
    basic_nmber = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='基本数量')
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                     validators=[MinValueValidator(0)], verbose_name='购货单价')
    cost_price = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                     validators=[MinValueValidator(0)], verbose_name='成本价')
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                       validators=[MinValueValidator(0)], verbose_name='含税单价')
    discount = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                   validators=[MinValueValidator(0)], verbose_name='折扣率')
    dis_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                    validators=[MinValueValidator(0)], verbose_name='折扣额')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                    validators=[MinValueValidator(0)], verbose_name='购货金额')
    tax_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                   validators=[MinValueValidator(0)], verbose_name='税率')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                    validators=[MinValueValidator(0)], verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='优惠率(%)')
    preferential_money = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='优惠后金额')
    purchase_money = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='0', null=True, blank=True,
                              verbose_name='状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', null=True, blank=True,
                                    verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0', null=True,
                                      blank=True, verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    library_number = models.IntegerField(default=0, verbose_name='未出库数量')
    library_money = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='未出库金额')
    library_time = models.IntegerField(null=True, blank=True, verbose_name='最后出库时间')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())

    class Meta:
        db_table = 'fa_kuyou_goods_sales_order_info'
        verbose_name = '销货订单详情'
        verbose_name_plural = '销货订单详情'

    def __str__(self):
        return f"{self.purchase_code or '无编号'}-{self.goods_code}"


# 销售单
class FaKuyouGoodsSales(models.Model):
    ORDER_TYPE_CHOICES = [
        ('1', '销货单'),
        ('2', '零售单'),
    ]

    PURCHASE_TYPE_CHOICES = [
        ('1', '销货'),
        ('2', '退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未收款'),
        ('1', '全部收款'),
        ('2', '部分收款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    order_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='零售编号')
    order_time = models.IntegerField(null=True, blank=True, verbose_name='零售时间')
    order_type = models.CharField(max_length=1, choices=ORDER_TYPE_CHOICES, default='1', verbose_name='单据类型')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期')
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    receiving_address = models.CharField(max_length=255, null=True, blank=True, verbose_name='收货地址')
    sale_user = models.IntegerField(null=True, blank=True, verbose_name='销售员ID')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='销货金额')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.FloatField(default=0.00, verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    customers_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='客户承担费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='收款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID', default=0)
    note = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                  verbose_name='本次欠款')
    all_arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='总欠款')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    cost_data = models.TextField(null=True, blank=True, verbose_name='采购销售费用')
    third_id = models.IntegerField(default=0, verbose_name='三方ID')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_goods_sales'
        verbose_name = '销货单'
        verbose_name_plural = '销货单'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['order_code']),
            models.Index(fields=['customers_id']),
        ]

    def save(self, *args, **kwargs):
        if self.pay_money < self.real_money:
            self.pay_status = '2'
        elif self.pay_money == self.real_money:
            self.pay_status = '1'
        else:
            self.pay_status = '0'

        # 计算欠款
        self.arrears = self.real_money - self.pay_money
        # 更新总欠款（供应商表中记录）
        supplier = FaKuyouCustomer.objects.filter(id=self.customers_id).first()
        self.all_arrears = supplier.need_receive_account + supplier.receive_account + float(self.arrears)
        supplier.save()

        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.get_order_type_display()}"


# 销售详情单
class FaKuyouGoodsSalesInfo(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '销货'),
        ('2', '退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未收款'),
        ('1', '部分收款'),
        ('2', '全部收款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期')
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    receiving_address = models.CharField(max_length=255, null=True, blank=True, verbose_name='收货地址')
    sale_user = models.IntegerField(null=True, blank=True, verbose_name='销售员ID')
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品备注')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库ID')
    allow_stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='可用库存')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='基本单位')
    basic_nmber = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='基本数量')
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='销货单价')
    cost_price = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='成本价',
                                     default=0)
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                       validators=[MinValueValidator(0)], verbose_name='含税单价')
    discount = models.FloatField(default=0.00, verbose_name='折扣率')
    dis_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='折扣额')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    tax_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                   verbose_name='税率')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.FloatField(default=0.00, verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    customers_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='客户承担费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='收款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    order_info_id = models.CharField(max_length=255, null=True, blank=True, verbose_name='购货订单详情ID')
    batch_id = models.IntegerField(null=True, blank=True, verbose_name='批次ID')
    batch_name = models.CharField(max_length=100, null=True, blank=True, verbose_name='批次名称')
    manufacture = models.IntegerField(null=True, blank=True, verbose_name='生产日期')
    guarantee = models.IntegerField(null=True, blank=True, verbose_name='保质期')
    validity = models.IntegerField(null=True, blank=True, verbose_name='有效期')
    period = models.TextField(null=True, blank=True, verbose_name='序列号')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_goods_sales_info'
        verbose_name = '商品销售明细'
        verbose_name_plural = '商品销售明细'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_code']),
            models.Index(fields=['stores_id']),
        ]

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.goods_code}"


# 销售订单关联表
class FaKuyouGoodsSaleord(models.Model):
    id = models.AutoField(primary_key=True)
    order_id = models.IntegerField(default=0, verbose_name='订单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='采购单ID')

    class Meta:
        db_table = 'fa_kuyou_goods_saleord'
        verbose_name = '销售订单关联'
        verbose_name_plural = '销售订单关联'
        indexes = [
            models.Index(fields=['order_id']),
            models.Index(fields=['purchase_id']),
        ]

    def __str__(self):
        return f"销售订单关联 {self.id} (订单:{self.order_id}, 采购:{self.purchase_id})"


# 销售订单关联详情表
class FaKuyouGoodsSaleordInfo(models.Model):
    STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理'),
    ]

    id = models.AutoField(primary_key=True)
    order_id = models.IntegerField(default=0, verbose_name='订单ID')
    purchase_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='销货明细ID'
    )
    number = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='数量'
    )
    money = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='已收款金额'
    )
    all_money = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='销货金额'
    )
    tax_rate = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='税率'
    )
    tax_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='税额'
    )
    money_tax_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='价税合计'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='处理状态'
    )
    times = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='处理次数'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_saleord_info'
        verbose_name = '销售订单关联明细'
        verbose_name_plural = '销售订单关联明细'
        indexes = [
            models.Index(fields=['order_id']),
            models.Index(fields=['purchase_id']),
            models.Index(fields=['status']),
        ]

    def __str__(self):
        return f"订单关联明细 {self.id} (订单:{self.order_id})"


# 销售退货单
class FaKuyouGoodsSalesExchange(models.Model):
    ORDER_TYPE_CHOICES = [
        ('1', '销货单'),
        ('2', '零售单'),
    ]

    PURCHASE_TYPE_CHOICES = [
        ('0', '退货'),
        ('1', '销货订单退货'),
        ('2', '销货单退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未收款'),
        ('1', '全部收款'),
        ('2', '部分收款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    RETREAT_STATUS_CHOICES = [
        ('0', '未退款'),
        ('1', '全部退款'),
        ('2', '部分退款'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    order_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='零售编号')
    order_time = models.IntegerField(null=True, blank=True, verbose_name='零售时间')
    order_type = models.CharField(max_length=1, choices=ORDER_TYPE_CHOICES, default='1', verbose_name='单据类型')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='0', verbose_name='退货类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期')
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    receiving_address = models.CharField(max_length=255, null=True, blank=True, verbose_name='收货地址')
    sale_user = models.IntegerField(null=True, blank=True, verbose_name='销售员ID')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    preferential_rate = models.FloatField(default=0.00, verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    customers_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='客户承担费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='收款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    retreat_status = models.CharField(max_length=1, choices=RETREAT_STATUS_CHOICES, null=True, blank=True,
                                      verbose_name='退款状态')
    retreat_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='退货数量')
    retreat_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                        validators=[MinValueValidator(0)], verbose_name='退款金额')
    note = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                  verbose_name='本次欠款')
    all_arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='总欠款')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    cost_data = models.TextField(null=True, blank=True, verbose_name='采购销售费用')
    third_id = models.IntegerField(default=0, verbose_name='三方ID')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_goods_sales_exchange'
        verbose_name = '销货退货单'
        verbose_name_plural = '销货退货单'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['order_code']),
            models.Index(fields=['customers_id']),
            models.Index(fields=['examine_status']),
        ]

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.get_purchase_type_display()}"


# 销售退货详情单
class FaKuyouGoodsSalesExchangeInfo(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('0', '默认类型'),
        ('1', '销货'),
        ('2', '退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未收款'),
        ('1', '全部收款'),
        ('2', '部分收款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    RETREAT_STATUS_CHOICES = [
        ('0', '未退款'),
        ('1', '全部退款'),
        ('2', '部分退款'),
    ]

    # 基础信息
    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, null=True, verbose_name='销售类型')

    # 时间信息
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期')
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    # 客户信息
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    receiving_address = models.CharField(max_length=255, null=True, blank=True, verbose_name='收货地址')
    sale_user = models.IntegerField(null=True, blank=True, verbose_name='销售员ID')

    # 商品信息
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品备注')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库ID')
    allow_stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='可用库存')

    # 数量信息
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='数量')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='基本单位')
    basic_nmber = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='基本数量')

    # 价格信息
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='购货单价')
    cost_price = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='成本价')
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='含税单价')
    discount = models.FloatField(default=0.00, verbose_name='折扣率')
    dis_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='折扣额')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='购货金额')
    tax_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='税率')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='价税合计')

    # 订单关联
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    purchase_info_id = models.IntegerField(null=True, blank=True, verbose_name='购货单详情ID')

    # 金额信息
    preferential_rate = models.FloatField(default=0.00, verbose_name='优惠率')
    preferential_money = models.FloatField(default=0.00, verbose_name='优惠额')
    real_money = models.FloatField(default=0.00, verbose_name='优惠后金额')
    purchase_money = models.FloatField(default=0.00, verbose_name='采购费用')
    customers_money = models.FloatField(default=0.00, verbose_name='客户承担费用')

    # 人员信息
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')

    # 状态信息
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='收款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    pay_money = models.FloatField(default=0.00, verbose_name='已付款金额')
    retreat_status = models.FloatField(default=0.00, verbose_name='退款状态')
    retreat_number = models.FloatField(default=0.00, verbose_name='退货数量')
    retreat_money = models.FloatField(default=0.00, verbose_name='退款金额')

    # 其他信息
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    batch_id = models.IntegerField(null=True, blank=True, verbose_name='批次ID')
    batch_name = models.CharField(max_length=100, null=True, blank=True, verbose_name='批次名称')
    manufacture = models.IntegerField(null=True, blank=True, verbose_name='生产日期')
    guarantee = models.IntegerField(null=True, blank=True, verbose_name='保质期')
    validity = models.IntegerField(null=True, blank=True, verbose_name='过期时间')
    period = models.TextField(null=True, blank=True, verbose_name='序列号')

    class Meta:
        db_table = 'fa_kuyou_goods_sales_exchange_info'
        verbose_name = '退货明细'
        verbose_name_plural = '退货明细'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_code']),
            models.Index(fields=['customers_id']),
            models.Index(fields=['examine_status']),
        ]

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.goods_code}"


# 销售退货关联表
class FaKuyouGoodsSaleExc(models.Model):
    TYPE_CHOICES = [
        ('0', '默认类型'),
        ('1', '销货单关联'),
        ('2', '退货单关联'),
    ]

    id = models.AutoField(primary_key=True)
    exchange_id = models.IntegerField(default=0, verbose_name='交换单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='采购单ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='0',
        verbose_name='单据类型'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_saleexc'
        verbose_name = '退单关联'
        verbose_name_plural = '退单关联'
        indexes = [
            models.Index(fields=['exchange_id']),
            models.Index(fields=['purchase_id']),
            models.Index(fields=['type']),
        ]

    def __str__(self):
        return f"退单关联 {self.id} (交换单:{self.exchange_id}, 采购单:{self.purchase_id})"


# 销货退货关联详情单
class FaKuyouGoodsSaleExcInfo(models.Model):
    TYPE_CHOICES = [
        ('0', '默认类型'),
        ('1', '销货订单'),
        ('2', '销货单'),
    ]

    STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    exchange_id = models.IntegerField(default=0, verbose_name='交换单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='采购单ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        null=True,
        verbose_name='关联类型'
    )
    number = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='数量'
    )
    money = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='退款金额'
    )
    all_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='购货金额'
    )
    tax_rate = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='税率'
    )
    tax_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='税额'
    )
    money_tax_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='价税合计'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    times = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='处理次数'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_saleexc_info'
        verbose_name = '退单关联明细'
        verbose_name_plural = '退单关联明细'
        indexes = [
            models.Index(fields=['exchange_id']),
            models.Index(fields=['purchase_id']),
            models.Index(fields=['type']),
            models.Index(fields=['status']),
        ]

    def save(self, *args, **kwargs):
        # 自动计算税额和价税合计
        if self.all_money and self.tax_rate:
            self.tax_money = float(self.all_money) * float(self.tax_rate) / 100
            self.money_tax_price = float(self.all_money) + float(self.tax_money)

        super().save(*args, **kwargs)

    def __str__(self):
        return f"退单明细 {self.id} (类型:{self.get_type_display()})"
